--
-- @Author:      feilong
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 客户端消息的处理

local skynet = require "skynet"
-- local config = require "configquery"
local ErrorCode = require("ErrorCode")


local ClientHandler = class("ClientHandler")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function ClientHandler:ctor(message_dispatch, node_message)

	self.message_dispatch = message_dispatch	
	self.node_message = node_message

	self:register()
end

--注册本服务里的消息
function ClientHandler:register()

	self:registerSelf('list', "serviceListReq")
	self:registerSelf('getGateReq', "getGateReq")

	self:registerSelf('add_user', "addUserReq")
	self:registerSelf('change_user', "changeUserReq")
	self:registerSelf('login_user', "loginUserReq")
	self:registerSelf('delete_user', "deleteUserReq")
	
	self:registerSelf('user_list', "userListReq")

	self:registerSelf('touristRegisterReq', "touristRegisterReq")
	
	self:registerSelf('game_user_list', "gameUserListReq")
	self:registerSelf('hotfix_service', "hotfixService")

end

function ClientHandler:registerSelf(message_name, callback)
	print("__webserver______message_name___", message_name)
	if not callback then 
		callback = message_name
	end	
	if not self[callback] then 
		error_log("__registerSelf_没有注册函数回调____",message_name)
	end
	self.message_dispatch:registerSelf(message_name, handler(self,self[callback]))
end

---------------------------------------------------------
-- CMD
---------------------------------------------------------



--服务列表
function ClientHandler:serviceListReq( data )
	print("____onList__",data)

	local list_res = self.node_message:callService(".console", "list")
	local mem_res = self.node_message:callService(".console", "mem")
	local stat_res = self.node_message:callService(".console", "stat")
	local data = {}
	local index = 0
	for k, v in pairs(list_res) do 
		local item = {}
		index = index + 1
		item.id = index
		item.service_id = string.sub(k,2)
		item.name = string.match(mem_res[k], "%(snlua (.+)%)$")
		item.mem = tonumber(string.match(mem_res[k], "(.+) Kb"))
		item.cpu= tonumber(stat_res[k].cpu)
		item.message= tonumber(stat_res[k].message)
		item.mqlen= tonumber(stat_res[k].mqlen)
		item.task= tonumber(stat_res[k].task)
		table.insert(data, item)
	end

	return {
		code= 0,
		msg= "",
		count= #data,
		data= data,		
	}

end

--用户列表
function ClientHandler:userListReq(data)
	print("____userListReq__",data)
	local curr = (data.curr-1)*data.nums
	local nums = data.nums 	
	local count_res = self.node_message:callDbMySqlEx("count", "user")
	print("__________count___", count_res)
	local count = count_res["count(*)"]
 	local res = self.node_message:callDbMySql("select * from user limit "..curr..","..nums) 	 	
	return {		
		code= 0, --规定数据状态的字段名称，默认：code
		msg= "", --规定状态信息的字段名称，默认：msg
		count= count,  --规定数据总数的字段名称，默认：count
		data= res,		
	}
end

--用户登录
function ClientHandler:loginUserReq( data )
	print("____onlogin__",data)
	local data = data.content
	local username = data.name
	local password = data.password
	local tbname = "user"
 	local res = self.node_message:callDbMySqlEx("exists", tbname, nil, {{user_name=username},{password=password}})
 	-- print("__________res___",res)	
	if res and next(res) then 		
		return {
			error_code=0,			
		}
	end
	return {error_code=1,}
end

--添加用户
function ClientHandler:addUserReq(data)
	print("____addUserReq__",data)
	local table_name = "user"
	local user_name = data.user_name
	local password = data.password
	local gold = tonumber(data.gold)
	local diamond = tonumber(data.diamond)
	local res = self.node_message:callDbMySqlEx("exists", table_name, nil, {{user_name=user_name},})
	print("________get_user_______",res)
	if res and next(res) then 
		--用户已存在，不能注册
		return {			
			error_code= ErrorCode.user_has_exist,			
		}						
	end	
 	local data = {
 		user_name = user_name,
 		password = password,
 		gold = gold,
 		diamond = diamond,
 	} 	
 	local res = self.node_message:callDbMySqlEx("insert", table_name, data )
 	print("_______res__", res)
	if not res or not next(res) then 		
		return {
			error_code = ErrorCode.sql_error, 
		}							
	end	 	
	return {
		error_code=0	
	}
end


--修改用户
function ClientHandler:changeUserReq(data)
	print("____changeUserReq__",data)
	local table_name = "user"
	local user_name = data.user_name
	local password = data.password
	local gold = tonumber(data.gold)
	local diamond = tonumber(data.diamond)
	local res = self.node_message:callDbMySqlEx("exists", table_name, nil, {{user_name=user_name},})
	if not res or not next(res) then 		
		return {
			error_code = ErrorCode.user_not_exist, 
		}						
	end	
 	local data = {
 		user_name = user_name,
 		password = password,
 		gold = gold,
 		diamond = diamond,
 	}
	-- local res = self.node_message:callDbProxy("update_user", data, {{user_name=user_name}})
	local res = self.node_message:callDbMySqlEx("update", table_name, data, {{user_name=user_name},})
	print("____res_1_",res)
	if not res or not next(res) then 		
		return {
			error_code = ErrorCode.user_has_exist, 
		}							
	end	
	--更新成功
	return {		
		error_code= 0,	
	}
end

--删除用户
function ClientHandler:deleteUserReq(data)
	print("____deleteUserReq__",data)
	local table_name = "user"
	local user_id = data.user_id		
	local res = self.node_message:callDbMySqlEx("exists", table_name, nil, {{user_id=user_id},})
	if not res or not next(res) then 		
		return {
			error_code = ErrorCode.user_not_exist, 
		}						
	end	
	local res = self.node_message:callDbMySqlEx("delete", table_name, nil, {{user_id=user_id},})
	print("____res_1_",res)
	if not res or not next(res) then 		
		return {
			error_code = ErrorCode.user_has_exist, 
		}							
	end	
	--更新成功
	return {		
		error_code= 0,	
	}	

end

--取网关ip port
function ClientHandler:getGateReq(msg)
	local client_type = msg.client_type
	local port = 12201
	if client_type == "websocket" then 
		port = 12202
	end
	return {
		error_code = 0,
		ip = "127.0.0.1",
		port = port,
	}
end


--游客注册
function ClientHandler:touristRegisterReq(msg)
	-- debug_log("_____ClientHandler__touristRegisterReq___", msg)
	--通过传过来的seed_key 与 package_channel 和新建的account_id 生成一个 key_token返回给客户端用于登录验证
	local key_token = "" .. msg.seed_token .. msg.package_channel

	
	return {
		key_token = key_token,
		uid = math.random(100,1000),
	}
end

--游戏用户列表
function ClientHandler:gameUserListReq(data)
	debug_log("____userListReq__",data)
	local curr = (data.curr-1)*data.nums
	local nums = data.nums 	
	local count_res = self.node_message:callDbMySqlEx("count", "game_user")
	debug_log("__________count___", count_res)
	local count = count_res["count(*)"]
 	local res = self.node_message:callDbMySql("select * from game_user limit "..curr..","..nums) 	 	
	return {		
		code= 0, --规定数据状态的字段名称，默认：code
		msg= "", --规定状态信息的字段名称，默认：msg
		count= count,  --规定数据总数的字段名称，默认：count
		data= res,		
	}
end


--游戏用户列表
function ClientHandler:hotfixService(data)
	local service_id = data.service_id
	print("__hotfixService___", data)
	self.node_message:callService(".console", "clearcache")	
	local cmd_str = "call ".. service_id .. " 'hotfix' "
	local stat_res = self.node_message:callService(".console", cmd_str)	
	if stat_res and stat_res[1] then 
		return {
			error_code = 0,
		}
	end
	return {error_code = -1,}
end

return ClientHandler